package binary;

public class Binary {
	/**
	 * Converts the given binary string to base-10
	 * @param bits - a binary string
	 * @return int - decimal value of specified bitstring
	 */
	public static int bits2int(String bits) {
		if (bits == null || bits.isEmpty())
			return 0;
		return Integer.parseInt(bits, 2);
	}
	
	/**
	 * Converts an int to an n-bit binary string.
	 * @param num - decimal ingteger to convert
	 * @param n - number of bits to output
	 * @return String - binary value of specified number
	 */
	public static String int2bits(int num, int n) {
		if (n == 0) 
			return "";
		String bin = Integer.toBinaryString(num);
		while (bin.length() < n)
			bin = '0' + bin;
		return bin;
	}
	
	/**
	 * Convert an ASCII string to binary
	 * @param asciiMssg - ASCII message string
	 * @return String - asciiMssg represented in 8-bit binary
	 */
	public static String ascii2bin(String asciiMssg) {
		String str = "";
		for (int i = 0; i < asciiMssg.length(); i++)
			str += String.format("%08d", Integer.parseInt(Integer.toBinaryString(asciiMssg.charAt(i))));
		return str;
	}
	
	/**
	 * Convert a bit string into ASCII
	 * @param binMssg - binary message string
	 * @return String - ASCII encoded binMssg
	 */
	public static String bin2ascii(String binMssg) {
		String str = "";
		String sub;
		binMssg = binMssg.substring(0, 8 * (binMssg.length() / 8));
		for (int i = 0; i < binMssg.length(); i += 8) {
			sub = binMssg.substring(i, i + 8);
			str += (char)Integer.parseInt(sub, 2);
		}
		return str;
	}
}
